<?php
/**
 * 后台管理员管理控制器
 * PHP version 5
 * @package   Antonia
 * @author    Antonia <471699715@qq.com>
 * @copyright 2016 Antonia.
 */
namespace Admin\Controller;
use Think;
class AdminsController extends AdmincommonController {
    /**
     * 显示管理员列表
     * @param HttpRequest $request
     * @return html
     * @author Antonia
     */
    public function index() {
        $filters = array();
        !empty($_POST['admin_name']) && $filters['admin_name'] = array('like','%' . remove_xss($_POST['admin_name']) . '%');
        !empty($_POST['admin_email']) && $filters['admin_email'] = array('like','%' . remove_xss($_POST['admin_email']) . '%');
        $admin = D("Admins");
        $_GET['p'] = $_POST['p'];
        $count = $admin->where($filters)->count();
        if (!empty($_POST['numPerPage'])){
            $numPerPage = $_POST['numPerPage'];
        } else {
            $numPerPage = 20;
        }
        $Page  =  new \Think\Page($count,$numPerPage);
        $list = $admin->limit($Page->firstRow.','.$Page->listRows)
            ->where($filters)
            ->relation(true)
            ->select();
        $newList = array();
        foreach($list as $l) {
            $group_ids = explode(',', trim($l['group_id'], ','));
            $map = array();
            $map['group_id']  = array('in', $group_ids);
            $Admingroups =D("Admingroups");
            $groupArr = $Admingroups->where($map)->field('group_name')->select();
            $groups = "";
            foreach($groupArr as $g) {
                $groups .= $g['group_name'] . ",";
            }
            $l['groups'] = rtrim($groups, ',');
            unset($l['group_id']);
            $newList[] = $l;
        }
        $this->assign('list',$newList);
        $this->assign('filters', $_POST);
        $this->assign ('totalCount', $count);
        $this->assign ('numPerPage', $Page->listRows);
        $this->assign ('currentPage', !empty($_GET['p'])?$_GET['p']:1);
        $this->display();
    }

    /**
     * 显示新增管理员页面
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function add() {
        $this->assign('groupsList',  D("Admingroups")->getOptions()); //群组列表
        $this->display('info');
    }

    /**
     * 处理新增
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function insert() {
        $admin = D("Admins");
        if ($vo = $admin->create()) {
            $vo['admin_pass']  = md5($_POST['admin_pass']);
            $rs = $admin->add($vo);

            if ($rs !== false) {
                $re['statusCode'] = "200";
                $re['message'] = "新增管理员成功!";
                $re['navTabId'] = "Adminsindex";
                $re['callbackType'] = "closeCurrent";
            } else {
                $re['statusCode'] = "300";
                $re['message'] = "新增管理员错误，请重试!";
            }
        } else {
                $re['statusCode'] = "300";
                $re['message'] = $admin->getError();
        }
        echo json_encode($re);
    }

    /**
     * 显示编辑页面
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function edit() {
        $admin_id = remove_xss($_GET['id']);
        if (!empty($admin_id)) {
            $admin     = D("Admins");
            $adminInfo = $admin->find($admin_id);
            if ($adminInfo) {
                $groups = D("Admingroups");
                $allgroups = $groups->getOptions();
                if ($adminInfo['group_id'] != "") {
                    $groupids = explode(',', trim($adminInfo['group_id'], ','));
                    $gidarr = array();
                    foreach ($allgroups as $k => $g) {
                        if($k == "") {
                            continue;
                        }
                        if(in_array($k, $groupids)) {
                            $gidarr[$k] = $allgroups[$k];
                            unset($allgroups[$k]);
                        }
                    }
                    $this->assign('gList', $gidarr);
                }
                $this->assign('groupsList', $allgroups); //群组列表
                $this->assign('admin', $adminInfo);
                $this->display('info');
            } else {
                $re['statusCode'] = "300";
                $re['navTabId'] = "Adminsindex";
                $re['message'] = "该管理员信息不存在！";
                echo json_encode($re);
            }
        } else {
                $re['statusCode'] = "300";
                $re['navTabId'] = "Adminsindex";
                $re['message'] = "该管理员信息不存在！";
                echo json_encode($re);
        }
    }

    /**
     * 处理更新数据
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function update() {
        $admin = D("Admins");
        $re = array();
        if ($vo = $admin->create()) {

            if ($_POST['admin_pass'] != "") {
                $vo['admin_pass']  = md5($_POST['admin_pass']);
            } else {
                unset($vo['admin_pass']);
            }
            
            $list = $admin->save($vo);

            if ($list !== false) {
                $re['statusCode'] = "200";
                $re['message'] = "管理员信息修改成功!";
                $re['navTabId'] = "Adminsindex";
            } else {
                $re['statusCode'] = "300";
                $re['message'] = "没有更新任何数据!";
            }
        } else {
                $re['statusCode'] = "300";
                $re['message'] = $admin->getError();
        }
        echo json_encode($re);
    }

    /**
     * 删除管理员
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function delete() {
        $re = array();
        if (!empty($_GET['id'])) {
            $admin = D("Admins");
            if($admin->checkAdmin($_GET['id'])) {
                $re['statusCode'] = "300";
                $re['message'] = "请先移除该管理员的群组关系后再执行删除操作.";
                echo json_encode($re);
                exit;
            }
            $result = $admin->delete(remove_xss($_GET['id']));
            if (false !== $result) {
                $re['statusCode'] = "200";
                $re['message'] = "删除成功!";
            } else {
                $re['statusCode'] = "300";
                $re['message'] = "删除失败，请重试!";
            }
        } else {
                $re['statusCode'] = "300";
                $re['message'] = "该记录不存在！";
        }
        echo json_encode($re);
    }

    /**
     * 删除选定内容
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function delAll() {
        $admin = D("Admins");
        $re = array();
        $map['admin_id']  = array('in', explode(',', $_POST["ids"]));
        $result  = $admin->where($map)->delete();
        if($result) {
            $re['statusCode'] = "200";
            $re['message'] = "删除成功!";
        } else {
            $re['statusCode'] = "300";
            $re['message'] = "删除失败，请重试!";
        }
        echo json_encode($re);
    }

    /**
     * 管理员列表ajax 单选
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function adminList () {
        $filters = array();
        !empty($_POST['admin_name']) && $filters['admin_name'] = array('like','%' . remove_xss($_POST['admin_name']) . '%');
        !empty($_POST['group']) && $filters['group_id'] = array('like','%,' . remove_xss($_POST['group']) . ',%');
        $admin = D("Admins");
        $_GET['p'] = $_POST['p'];
        if (!empty ($_POST['orderField'] )) {
            $orderField = $_POST['orderField'];
        } else {
            $orderField = ! empty ( $sortBy ) ? $sortBy : $admin->getPk();
        }
        if (isset ( $_POST['orderDirection'] )) {
            $orderDirection = $_POST['orderDirection'] == 'asc' ? 'asc' : 'desc';
        } else {
            $orderDirection = 'desc';
        }
        if (!empty($_POST['numPerPage'])){
            $numPerPage = $_POST['numPerPage'];
        } else {
            $numPerPage = 20;
        }
        $count = $admin->where($filters)->count();
        $Page  =  new \Think\Page($count,$numPerPage);
        $list = $admin->order($orderField . " " . $orderDirection)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->where($filters)
            ->field('admin_id, name, group_id, role_id, section_id')
            ->select();
        $newList = array();
        foreach($list as $l) {
            $group_ids = explode(',', trim($l['group_id'], ','));
            $map = array();
            $map['group_id']  = array('in', $group_ids);
            $Admingroups =D("Admingroups");
            $groupArr = $Admingroups->where($map)->field('group_name')->select();
            $groups = "";
            foreach($groupArr as $g) {
                $groups .= $g['group_name'] . ",";
            }
            $l['groups'] = rtrim($groups, ',');
            unset($l['group_id']);
            $newList[] = $l;
        }
        $Admingroups = D("Admingroups");
        $this->assign('groups', $Admingroups->getOptions());
        $this->assign('list',$newList);
        $this->assign ('orderDirection', $orderDirection);
        $this->assign ('orderField', $orderField);
        $this->assign('filters', $_POST);
        $this->assign ('totalCount', $count);
        $this->assign ('numPerPage', $Page->listRows);
        $this->assign ('currentPage', !empty($_GET['p'])?$_GET['p']:1);
        $this->display('adminlist');
    }

    /**
     * 管理员列表ajax 复选
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function multiAdminList() {
        $filters = array();
        !empty($_POST['admin_name']) && $filters['admin_name'] = array('like','%' . remove_xss($_POST['admin_name']) . '%');
        !empty($_POST['group']) && $filters['group_id'] = array('like','%,' . remove_xss($_POST['group']) . ',%');
        $admin = D("Admins");
        $_GET['p'] = $_POST['p'];
        if (!empty ($_POST['orderField'] )) {
            $orderField = $_POST['orderField'];
        } else {
            $orderField = ! empty ( $sortBy ) ? $sortBy : $admin->getPk();
        }
        if (isset ( $_POST['orderDirection'] )) {
            $orderDirection = $_POST['orderDirection'] == 'asc' ? 'asc' : 'desc';
        } else {
            $orderDirection = 'desc';
        }
        if (!empty($_POST['numPerPage'])){
            $numPerPage = $_POST['numPerPage'];
        } else {
            $numPerPage = 1;
        }
        $count = $admin->where($filters)->count();
        $Page  =  new \Think\Page($count,$numPerPage);
        $list = $admin->order($orderField . " " . $orderDirection)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->where($filters)
            ->field('admin_id, admin_name, name, group_id')
            ->select();
        $newList = array();
        foreach($list as $l) {
            $group_ids = explode(',', trim($l['group_id'], ','));
            $map = array();
            $map['group_id']  = array('in', $group_ids);
            $Admingroups =D("Admingroups");
            $groupArr = $Admingroups->where($map)->field('group_name')->select();
            $groups = "";
            foreach($groupArr as $g) {
                $groups .= $g['group_name'] . ",";
            }
            $l['groups'] = rtrim($groups, ',');
            unset($l['group_id']);
            $newList[] = $l;
        }
        $Admingroups = D("Admingroups");
        $this->assign('groups', $Admingroups->getOptions());
        $this->assign('list',$newList);
        $this->assign ('orderDirection', $orderDirection);
        $this->assign ('orderField', $orderField);
        $this->assign('filters', $_POST);
        $this->assign ('totalCount', $count);
        $this->assign ('numPerPage', $Page->listRows);
        $this->assign ('currentPage', !empty($_GET['p'])?$_GET['p']:1);
        $this->display('multiadminlist');
    }
    
    /**
     * 所有管理员 ajax 单选
     * @param HttpRequest $request
     * @return void
     * @author Antonia
    */
    public function allAdminRadio() {
        $Sections = D("Sections");        
        $sections = $Sections->getSectionAdmin();
        $list = $this->eachSectionChild($sections);
        $this->assign('list',$list);
        $this->display('alladminradio');
    }

    private function eachSectionChild($sections) {
        $newSections = array();
        $Admins = D("Admins");
        foreach ($sections as $val) {
            $section_id = $val['section_id'];
            $filters = array();
            $filters['section_id'] = array('like','%,' . $section_id . ',%');
            $admins = $Admins->where($filters)->field('admin_id,name')->select();
            $val['admins'] = $admins;
            if(!empty($val['children'])) {
                $val['children'] = $this->eachSectionChild($val['children']);
            }
            $newSections[] = $val;
        }
        return $newSections;
    }

}
?>